package com.jc.nio.log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 本类用于构造动态代理对象
 * @author Ervin.zhang
 */
public class ProxyFactory
{

    /**
     * 构造动态代理对象
     * @param target 被代理对象
     * @param advice 方法通知
     * @return 代理对象
     */
    public static <T> T getProxy(final T target, final LogAdvice advice)
    {
        return (T) Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){
        	public Object invoke(Object proxy, Method method, Object[] args){
	            advice.before(method, args);
	            long startTime = System.currentTimeMillis();
	            Object result = null;
	            try
	            {
	                result = method.invoke(target, args);
	            }
	            catch (Exception e)
	            {
	                try {
						advice.tryCatch(e);
					} catch (Throwable e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	            }
	            long endTime = System.currentTimeMillis();
	            advice.after(method, args, endTime - startTime, result);
	            return result;
        	}
        });
    }
}
